<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="phone"
          left-icon="phone"
          name="phone"
          label="手机号"
          placeholder="请填写手机号"
          type="tel"
          size="large"
          clearable
      />
      <van-field
          v-model="userCode"
          center
          type="digit"
          left-icon="setting"
          name="userPassword"
          label="验证码"
          placeholder="请填写验证码"
          size="large"
          style="margin-top: 1vh"
          clearable
      >
        <template #button>
          <van-button style="margin-left: 1vw" v-if="!countdown" @click="sendCode" size="small" type="primary">发送验证码</van-button>
          <van-button v-else size="small">{{ remainingTime }}s</van-button>
        </template>
      </van-field>
    </van-cell-group>


    <div style="margin-top: 10vh;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
</template>


<script setup>
import { ref} from "vue";
import {showToast} from "vant";


const phone = ref('');
const userCode = ref('');
const countdown = ref(false);
const remainingTime = ref(60);



const onSubmit = () => {
  //校验参数
  if (phone.value.length != 11){
    showToast("手机号不正确");
    return;
  }

  if (userCode.value == ''){
    showToast("请填写验证码");
    return;
  }

  const data = {
    phone: phone.value,
    code: userCode.value
  };

  //调用登录接口
};



//发送验证码方法
const sendCode = ()=>{
  //不能一直发送
  if (remainingTime.value!=60){
    return;
  }

  //校验
  if (phone.value == ''){
    showToast("请填写手机号");
    return;
  }
  if (phone.value.length !== 11){//手机号11位
    showToast("手机号不正确");
    return;
  }

  //调用接口发验证码，倒计时60秒
  countdown.value = true;
  const timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(timer);
      countdown.value = false;
      remainingTime.value = 60;
    }
  }, 1000);
};


</script>



<style scoped>

</style>